package com.sakhalin.news.viewmodels


import androidx.lifecycle.viewModelScope
import com.sakhalin.news.BuildConfig
import com.sakhalin.news.models.news.NewsCategoryItem
import com.sakhalin.news.network.DataLoadingState
import com.sakhalin.news.repositories.NewsCategoriesRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class NewsCategoriesViewModel : BaseViewModel() {

    private val newsCategoriesRepository = NewsCategoriesRepository()

    private val _newsCategoriesState = MutableStateFlow(emptyList<NewsCategoryItem>())
    val newsCategoriesState: StateFlow<List<NewsCategoryItem>> get() = _newsCategoriesState

    init {
        getCategories()
    }

    fun getCategories() {
        viewModelScope.launch {

            try {
                _loadingState.value = DataLoadingState.Loading()
                val response = newsCategoriesRepository.getNewsCategories()

                if (response.isError) {
                    _loadingState.value = DataLoadingState.ErrorLoading(response.errorText)
                }

                val content = checkNotNull(response.content)
                _newsCategoriesState.value = content

                _loadingState.value = DataLoadingState.LoadingSuccess()

            } catch (e: Exception) {
                e.printStackTrace()

                _loadingState.value = DataLoadingState.ErrorLoading(
                    if (BuildConfig.DEBUG) e.message ?: "Неизвестная ошибка"
                    else NO_DATA_ERROR_TEXT
                )
            }
        }
    }

}